import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/api_response.dart';
import '../../models/timeline_event.dart';
import '../../models/memory.dart';
import '../timeline_repository.dart';
import '../../services/mock_api_service.dart';

class MockTimelineRepository implements TimelineRepository {
  static const String _memoriesKey = 'memories';
  static const String _eventsKey = 'timeline_events';
  
  @override
  Future<ApiResponse<List<Memory>>> getAllMemories() async {
    return MockApiService.simulateApiCall<List<Memory>>(() async {
      final prefs = await SharedPreferences.getInstance();
      final jsonList = prefs.getStringList(_memoriesKey) ?? [];
      
      final memories = jsonList
          .map((json) => Memory.fromJson(jsonDecode(json)))
          .toList()
        ..sort((a, b) => b.date.compareTo(a.date));
      
      return memories;
    });
  }
  
  @override
  Future<ApiResponse<Memory>> getMemoryById(String id) async {
    return MockApiService.simulateApiCall<Memory>(() async {
      final response = await getAllMemories();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取回忆数据失败');
      }
      
      final memory = response.data!.firstWhere(
        (memory) => memory.id == id,
        orElse: () => throw Exception('未找到指定的回忆'),
      );
      
      return memory;
    });
  }
  
  @override
  Future<ApiResponse<Memory>> createMemory(Memory memory) async {
    return MockApiService.simulateApiCall<Memory>(() async {
      final response = await getAllMemories();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取回忆数据失败');
      }
      
      final memories = response.data!;
      memories.add(memory);
      memories.sort((a, b) => b.date.compareTo(a.date));
      
      await _saveMemoriesToStorage(memories);
      
      return memory;
    });
  }
  
  @override
  Future<ApiResponse<Memory>> updateMemory(Memory memory) async {
    return MockApiService.simulateApiCall<Memory>(() async {
      final response = await getAllMemories();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取回忆数据失败');
      }
      
      final memories = response.data!;
      final index = memories.indexWhere((m) => m.id == memory.id);
      if (index == -1) {
        throw Exception('未找到要更新的回忆');
      }
      
      memories[index] = memory;
      memories.sort((a, b) => b.date.compareTo(a.date));
      await _saveMemoriesToStorage(memories);
      
      return memory;
    });
  }
  
  @override
  Future<ApiResponse<void>> deleteMemory(String id) async {
    return MockApiService.simulateVoidApiCall(() async {
      final response = await getAllMemories();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取回忆数据失败');
      }
      
      final memories = response.data!;
      memories.removeWhere((memory) => memory.id == id);
      await _saveMemoriesToStorage(memories);
    });
  }
  
  @override
  Future<ApiResponse<List<TimelineEvent>>> getAllEvents() async {
    return MockApiService.simulateApiCall<List<TimelineEvent>>(() async {
      final prefs = await SharedPreferences.getInstance();
      final jsonList = prefs.getStringList(_eventsKey) ?? [];
      
      final events = jsonList
          .map((json) => TimelineEvent.fromJson(jsonDecode(json)))
          .toList()
        ..sort((a, b) => b.date.compareTo(a.date));
      
      return events;
    });
  }
  
  @override
  Future<ApiResponse<TimelineEvent>> getEventById(String id) async {
    return MockApiService.simulateApiCall<TimelineEvent>(() async {
      final response = await getAllEvents();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取时间线事件数据失败');
      }
      
      final event = response.data!.firstWhere(
        (event) => event.id == id,
        orElse: () => throw Exception('未找到指定的时间线事件'),
      );
      
      return event;
    });
  }
  
  @override
  Future<ApiResponse<TimelineEvent>> createEvent(TimelineEvent event) async {
    return MockApiService.simulateApiCall<TimelineEvent>(() async {
      final response = await getAllEvents();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取时间线事件数据失败');
      }
      
      final events = response.data!;
      events.add(event);
      events.sort((a, b) => b.date.compareTo(a.date));
      
      await _saveEventsToStorage(events);
      
      return event;
    });
  }
  
  @override
  Future<ApiResponse<TimelineEvent>> updateEvent(TimelineEvent event) async {
    return MockApiService.simulateApiCall<TimelineEvent>(() async {
      final response = await getAllEvents();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取时间线事件数据失败');
      }
      
      final events = response.data!;
      final index = events.indexWhere((e) => e.id == event.id);
      if (index == -1) {
        throw Exception('未找到要更新的时间线事件');
      }
      
      events[index] = event;
      events.sort((a, b) => b.date.compareTo(a.date));
      await _saveEventsToStorage(events);
      
      return event;
    });
  }
  
  @override
  Future<ApiResponse<void>> deleteEvent(String id) async {
    return MockApiService.simulateVoidApiCall(() async {
      final response = await getAllEvents();
      if (!response.isSuccess || response.data == null) {
        throw Exception('获取时间线事件数据失败');
      }
      
      final events = response.data!;
      events.removeWhere((event) => event.id == id);
      await _saveEventsToStorage(events);
    });
  }
  
  Future<void> _saveMemoriesToStorage(List<Memory> memories) async {
    final prefs = await SharedPreferences.getInstance();
    final jsonList = memories.map((memory) => jsonEncode(memory.toJson())).toList();
    await prefs.setStringList(_memoriesKey, jsonList);
  }
  
  Future<void> _saveEventsToStorage(List<TimelineEvent> events) async {
    final prefs = await SharedPreferences.getInstance();
    final jsonList = events.map((event) => jsonEncode(event.toJson())).toList();
    await prefs.setStringList(_eventsKey, jsonList);
  }
}